package com.sky.service.impl;


import com.aliyun.oss.common.utils.StringUtils;
import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrdersMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.util.StringUtil;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class reportServiceImpl implements ReportService {
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private WorkspaceService workspaceService;
    /*
    * 统计指定时间内的营业额数据
    * @param begin
    * @param end
    * @return
    * */
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        //1.获取时间列表
        List<LocalDate> dateList = getDateList(begin, end);
        //将带中括号的字符列表去除中括号
        String translated = translate(dateList);

        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate date : dateList) {
            //2.查询每个时间点的营业额
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map map = new HashMap<>();
            map.put("begin", beginTime);
            map.put("end", endTime);
            map.put("status",Orders.COMPLETED);
            Double turnover = ordersMapper.sumByMap(map);
            turnover = turnover == null ? 0.0 : turnover;
            turnoverList.add(turnover);
        }

        return TurnoverReportVO
                .builder()
                .dateList(translated)
                .turnoverList(StringUtil.join(",", turnoverList).replace("[","").replace("]",""))
                .build();
    }

    /*
    *
    * 统计指定时间内的用户数据
    * @param begin
    * @param end
    * @return
    * */
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        //1.获取时间列表
        List<LocalDate> dateList = getDateList(begin, end);
        //将带中括号的字符列表去除中括号
        String translated = translate(dateList);

        //2.查询每个时间点的用户数据
        List<Integer> totalUserList = new ArrayList<>();
        //3.查询每个时间点的新增用户数据
        List<Integer> newUserList = new ArrayList<>();
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map map = new HashMap<>();
            //总用户数量
            map.put("end", endTime);
            Integer user = ordersMapper.countByMap(map);
            user = user == null ? 0 : user;
            //新增用户数量
            map.put("begin", beginTime);
            Integer newUser = ordersMapper.countByMap(map);
            newUser = newUser == null ? 0 : newUser;
            //
            totalUserList.add(user);
            newUserList.add(newUser);
        }
        //4.返回结果
        return UserReportVO
                .builder()
                .dateList(translated)
                .totalUserList(StringUtil.join(",", totalUserList).replace("[","").replace("]",""))
                .newUserList(StringUtil.join(",", newUserList).replace("[","").replace("]",""))
                .build();
    }

    /**
     * 统计指定时间内的订单数据
     * @param begin
     * @param end
     * @return
     */
    public OrderReportVO getOrderStatistics(LocalDate begin, LocalDate end) {
        //1.获取时间列表
        List<LocalDate> dateList = getDateList(begin, end);
        //将带中括号的字符列表去除中括号
        String translated = translate(dateList);

        //2.查询每个时间点的订单数据
        List<Integer> orderCountList = new ArrayList<>();
        //将带中括号的字符列表去除中括号
        String translatedOrderCountList = translate(orderCountList);
        //3.查询每个时间点的有效订单数据
        List<Integer> validOrderCountList = new ArrayList<>();
        //将带中括号的字符列表去除中括号
        String translatedValidOrderCountList = translate(validOrderCountList);

        for (LocalDate date : dateList) {
            //开始时间和结束时间
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            Map map = new HashMap<>();
            map.put("end", endTime);
            map.put("begin", beginTime);
            //总订单数量
            Integer orderCount = ordersMapper.countReportByMap(map);
            orderCount = orderCount == null ? 0 : orderCount;
            //有效订单数量

            map.put("status",Orders.COMPLETED);
            Integer validOrderCount = ordersMapper.countReportByMap(map);
            validOrderCount = validOrderCount == null ? 0 : validOrderCount;

            orderCountList.add(orderCount);
            validOrderCountList.add(validOrderCount);
        }
        //时间区间内的总订单数量
        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();
        //时间区间内的有效订单数量
        Integer validOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();
        //4.计算订单完成率
        Double orderCompletionRate = 0.0;
        if (totalOrderCount != 0){
            orderCompletionRate = validOrderCount.doubleValue() / totalOrderCount;
        }
        //5.返回结果
        return OrderReportVO
                .builder()
                .dateList(translated)
                .orderCountList(StringUtil.join(",", orderCountList).replace("[","").replace("]",""))
                .validOrderCountList(StringUtil.join(",", validOrderCountList).replace("[","").replace("]",""))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }
    /**
    * 统计指定时间内的销量排名前10的数据
    * @param begin
    * @param end
    * @return`
    * */
    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end) {
        log.info("统计指定时间内的销量排名前10的数据{},{}", begin,end);

        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

        List<GoodsSalesDTO> salesTop10 = ordersMapper.getSalesTop10(beginTime, endTime);
        List<String> names = salesTop10.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        String nameList = StringUtils.join(",",names);

        List<Integer> numbers = salesTop10.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        String numberList = translate(numbers);


        return SalesTop10ReportVO
                .builder()
                .nameList(nameList)
                .numberList(numberList)
                .build();
    }

    /**
    * 导出数据
    * @param response
    * */
    public void exportBusinessData(HttpServletResponse response) {
        LocalDate dateBegin = LocalDate.now().minusDays(30);
        LocalDate dateEnd = LocalDate.now().minusDays(1);
        //查询概览数据
        BusinessDataVO businessDataVO = workspaceService.getBusinessData(LocalDateTime.of(dateBegin, LocalTime.MIN), LocalDateTime.of(dateEnd, LocalTime.MAX));
        //2.导出数据
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        try {
            XSSFWorkbook excel = new XSSFWorkbook(in);
            //3.填充数据,获取到sheet1,并填充数据
            XSSFSheet sheet1 = excel.getSheet("Sheet1");
            //获取到第二行
            XSSFRow  row = sheet1.getRow(1);
            row.getCell(1).setCellValue("时间：" + dateBegin + "至" + dateEnd);
            //获取到第四行
            row = sheet1.getRow(3);
            row.getCell(2).setCellValue(businessDataVO.getTurnover());
            row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessDataVO.getNewUsers());
            //获取到第五行
            row = sheet1.getRow(4);
            row.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            row.getCell(4).setCellValue(businessDataVO.getUnitPrice());

            //填充明细数据
            for (int i = 0; i < 30; i++) {
                LocalDate date = dateBegin.plusDays(1);
                //查询某一天的营业数据
                BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
                row = sheet1.getRow(7 + i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessData.getTurnover());
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData.getUnitPrice());
                row.getCell(6).setCellValue(businessData.getNewUsers());
            }


            //3.通过输出流将Excel文件下载到客户端浏览器
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);
            //关闭资源
            out.close();
            excel.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }



    //抽取出：获取时间列表方法
    private List<LocalDate> getDateList(LocalDate begin, LocalDate end){
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)){
            //日期计算，每次加一天
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        return dateList;
    }
    //抽取出：将带中括号的字符列表去除中括号
    private String translate(Object obj){
        String numberList = StringUtils.join(",", String.valueOf(obj));
        numberList = numberList.replace("[","");
        numberList = numberList.replace("]","");
        return numberList;
    }
}
